﻿using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Drawing;
using System.IO;
using System.Configuration;

/// <summary>
/// WebService の概要の説明です
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{

    public WebService()
    {

        //デザインされたコンポーネントを使用する場合、次の行をコメントを解除してください 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    /// <summary>
    /// 認証
    /// </summary>
    /// <param name="pass">パスワード文字列</param>
    /// <returns></returns>
    private bool CheckPassword(string pass)
    {
        string cPass = ConfigurationManager.AppSettings["Pass"];

        //if (pass == "pass") return true;
        if (pass == cPass) return true;
        else
        {
            System.Threading.Thread.Sleep(1000);
            return false;
        }
    }

    [WebMethod]
    public string Load(string file, string pass)
    {
        DeleteExpiredFiles();

        string s = "";
        if (CheckPassword(pass))
        {
            string path = Server.MapPath("data");
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            if (dirInfo.Exists)
            {
                FileInfo[] info = dirInfo.GetFiles(file + ".ks.xml");
                if (info.Length > 0)
                {
                    FileInfo theInfo = info[0];
                    using (StreamReader sr = theInfo.OpenText())
                    {
                        s = sr.ReadToEnd();
                    }
                }
            }
        }
        return s;
    }

    [WebMethod]
    public string GetLoadUrl(string file, string pass)
    {
        DeleteExpiredFiles();

        string s = "";
        if (CheckPassword(pass))
        {
            string path = Server.MapPath("data");
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            if (dirInfo.Exists)
            {
                FileInfo[] info = dirInfo.GetFiles(file + ".ks.xml");
                if (info.Length > 0)
                {
                    FileInfo theInfo = info[0];
                    string resultUriBase = ConfigurationManager.AppSettings["BaseUri"];
                    s = resultUriBase + "data/" + info[0].ToString();

                }
            }
        }
        return s;
    }

    //[WebMethod]
    //public byte[] LoadImage(string file, int dx, int dy, int x, int y, int width, int height, string pass)
    //{
    //    byte[] b = null;
    //    if (CheckPassword(pass))
    //    {
    //        MemoryStream ms = new MemoryStream();
    //        Qurihara.KotodamaPanel kPanel = new Qurihara.KotodamaPanel();
    //        kPanel.LocalApp = false;
    //        kPanel.Width = 640;
    //        kPanel.Height = 480;
    //        kPanel.Init();
    //        kPanel.LoadXml = this.Load(file, pass);
    //        //Bitmap bm = kPanel.SaveImage(ratio,x,y,width,height);
    //        Bitmap bm = kPanel.SaveImage(dx, dy, x, y, width, height);
    //        bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
    //        kPanel.DisposeResources();
    //        ms.Close();
    //        b = ms.GetBuffer();
    //    }
    //    return b;
    //}

    [WebMethod]
    public string Save(string xml, string pass)
    {
        DeleteExpiredFiles();

        string s = "";
        if (CheckPassword(pass) && xml.IndexOf("KOTODAMA") >= 0)
        {
            string path = Server.MapPath("data");
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            if (dirInfo.Exists)
            {
                string fileName = "q" + DateTime.Now.Ticks.ToString();

                string FilePath = Path.Combine(path, fileName + ".ks.xml");

                using (StreamWriter sw = File.CreateText(FilePath))
                {
                    sw.Write(xml);
                }
                string baseDir = ConfigurationManager.AppSettings["BaseUri"];

                s = fileName;
                //s = baseDir + "data/" + fileName + ".ks.xml";
                    //"viewer.aspx?id=" + fileName;
                    //"http://bunkin.net/kotopad/kotopad.aspx?f=" + fileName;
            }
        }
        return s;
    }

    private void DeleteExpiredFiles()
    {
        string expdaysS = ConfigurationManager.AppSettings["FileExpiredDays"];
        int expdays = 1;
        int.TryParse(expdaysS, out expdays);
        if (expdays > 0)
        {
            DirectoryInfo dinf = new DirectoryInfo(Server.MapPath("data"));
            foreach (FileInfo file in dinf.GetFiles())
            {
                //if (file.CreationTime.AddHours(expdays) < DateTime.Now)
                if (file.CreationTime.AddDays(expdays) < DateTime.Now)
                {
                    file.Delete();
                }
            }
        }
    }

    [WebMethod]
    public string GetSiteLocalImageUrl(string url,bool coerce, string pass)
    {
        DeleteExpiredFiles();

        string resultURL = "";
        if (CheckPassword(pass))
        {
            System.Net.WebClient wcl = new System.Net.WebClient();
            string path = Server.MapPath("data");
            string resultUriBase = ConfigurationManager.AppSettings["BaseUri"];
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            if (dirInfo.Exists)
            {
                string fileName = HttpUtility.UrlEncode(url).Replace("%","_") + ".png";//.Replace(".", "_");
                string FilePath = Path.Combine(path, fileName);
                resultURL = resultUriBase + "data/" + fileName;
                if (!File.Exists(FilePath) || coerce)
                {
                    try
                    {
                        //if (fileName.EndsWith("jpg") ||
                        //    fileName.EndsWith("bmp") ||
                        //    fileName.EndsWith("png") ||
                        //    fileName.EndsWith("gif")
                        //    )
                        if (url.EndsWith("jpg") ||
                            url.EndsWith("bmp") ||
                            url.EndsWith("png") ||
                            url.EndsWith("gif")
                            )
                        {
                            wcl.DownloadFile(new Uri(url), FilePath);
                        }
                        else
                        {
                            CreateImage(url,FilePath);
                        }
                    }
                    //catch (System.Net.WebException e)
                    catch (System.Exception e)
                    {
                        resultURL = "";
                        //WriteErrLog(url + "," + e.Message);
                    }
                }
            }

        }
        return resultURL;
    }

    private void CreateImage(string srcUrl, string destPath)
    {
        //srcUrl = Server.UrlDecode(srcUrl);
        string binpath = Server.MapPath("bin\\CrenaHtml2jpg");
        //string binpath = Server.MapPath("bin\\proccmd");
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.FileName = binpath;
        p.StartInfo.UseShellExecute = true;
        p.StartInfo.CreateNoWindow = true;
        //string outpath = htmlpath + ".png";
        string outpath = destPath;
        p.StartInfo.Arguments = "-o\"" + outpath + "\" -fpng -w800x600 -s800x600 -t25 -p -r -u\"" + srcUrl + "\"";
        //p.StartInfo.Arguments = "-w 30 -c " + capbinpath + " -o\"" + outpath + "\" -fpng -w800x600 -s117x90 -q92 -t25 -u\"" + srcUrl + "\"";
        p.Start();
        p.WaitForExit(30000);
        if(!p.HasExited) p.Kill();
        //File.Copy(outpath, destpath, true);
        p.Dispose();
        if (!File.Exists(destPath)) throw new Exception("image capture error");
    }


}

